package com.smrtcold.dev.task;

import com.smrtcold.dev.init.SystemInit;
import com.smrtcold.dev.dto.dev.task.DevTask;
import com.smrtcold.dev.dto.dev.base.XMZDevInfo;
import com.smrtcold.dev.service.base.BaseServer;
import com.smrtcold.dev.utils.Utils;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Log4j2
@Service
public class ReadDataJobExecution implements Job {

    @Autowired
    private BaseServer baseServer;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        DevTask devTask = (DevTask) context.getMergedJobDataMap().get("TASK");
        String apid = devTask.getApid();
        String[] devids = devTask.getDevids().split(",");
        StringBuffer msg=new StringBuffer();
        for (String devid : devids) {
            this.excp(devTask, apid, devid,msg);
        }
         this.baseServer.push(String.format("/%s/all/log/%s/%s", apid,  devTask.getMid(), devTask.getId()), msg.toString());
    }

    private boolean excp(DevTask devTask, String apid, String devid, StringBuffer msg) {
        XMZDevInfo plcjob = SystemInit.get(devid);
        if (null == plcjob) return true;
        try {
            Map<String, Number> datas = (Map<String, Number>) plcjob.readll(false, true);
            //log.info("读取数据.....设备：{},记录：{}", devid, datas.size());
            if (datas.isEmpty()) return true;
            //todo 转发到·mqtt
            // log.info("任务执行成功  - ：{}", devid, Utils.GSON.toJson(datas));
            this.baseServer.push(String.format("/%s/%s/data", apid, devid), Utils.GSON.toJson(datas));
           // this.baseServer.push(String.format("/%s/%s/log/%s/%s", apid, devid, devTask.getMid(), devTask.getId()), "上传成功："+datas.size());
            msg.append(String.format("%s->：%s \r\n", devid, datas.size()));
            return true;
        } catch (Exception e) {
            log.error("任务执行异常{}  - ：{}",devid, e);
            msg.append(String.format("%s->失败：%s \r\n", devid, e.getMessage()));
        }
        return false;
    }
}
